package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import classes.Narudzbenica;

public class NarudzbenicaDAO {
	@SuppressWarnings("unused")
	private final Connection c;
	private final PreparedStatement qInsert;
	private final PreparedStatement qDelete;
	private final PreparedStatement qSelectId;
	private final PreparedStatement qSelectAll;
	private final PreparedStatement qUpdate;

	public NarudzbenicaDAO(Connection c) throws Exception {
		this.c = c;
		qInsert=c.prepareStatement("INSERT INTO narudzbenica( datum, Korisnik_idKorisnik) VALUES (?,?)");
		qDelete = c.prepareStatement("DELETE FROM narudzbenica WHERE idNarudzbenica=?");
		qSelectId = c.prepareStatement("SELECT * FROM narudzbenica WHERE idNarudzbenica=?");
		qSelectAll = c.prepareStatement("SELECT * FROM narudzbenica");
		qUpdate=c.prepareStatement("UPDATE  narudzbenica SET idNarudzbenica=?, datum=?, Korisnik_idKorisnik=?");
		
	}
	
	public int insertNarudzenica(Narudzbenica n) throws Exception {
		try {
			qInsert.setDate(1, n.getDatum());
			qInsert.setInt(2, n.getKorisnik().getId());
			int a=qInsert.executeUpdate();
			return a; 
		} catch(Exception e) {
			e.printStackTrace(); 
			return 0;
		} 
	}
	
	public int updateNarudzbenica(Narudzbenica n) throws Exception {
		try{
		if (n==null)
			throw new Exception("Nije moguce mijenjati nepostojecu narudzbenica!");
		
		qSelectId.setInt(1, n.getIdNarudzbenica());
		ResultSet rs = qSelectId.executeQuery();
		rs.next();
		qUpdate.setInt(1, rs.getInt(1)+1);
		qUpdate.setDate(2, n.getDatum());
		qUpdate.setInt(3, n.getKorisnik().getId());

		return qUpdate.executeUpdate();
		
		} catch(Exception e){
			e.printStackTrace();
			return 0;
		}
	}
		
	public int deleteNarudzbenica(int id) throws Exception {
		qDelete.setInt(1, id);
		return qDelete.executeUpdate();
	}
	
	public Narudzbenica selectNarudzbenica(int id) throws Exception {
		qSelectId.setInt(1, id);
		ResultSet rs = qSelectId.executeQuery();
		if (rs.next()==false)
			throw new Exception("Nema takve narudzbenice");
		return ucitajNarudzbenicuIzResultSeta(rs);
	}
		
	public List<Narudzbenica> selectSveNarudzbenice() throws Exception{
		ResultSet rs = qSelectAll.executeQuery();
		List<Narudzbenica> naruceno = new ArrayList<Narudzbenica>();
		while (rs.next()){
			naruceno.add(ucitajNarudzbenicuIzResultSeta(rs));
		}
		return naruceno;
	}
	
		//pomocna funkcija
	private Narudzbenica ucitajNarudzbenicuIzResultSeta(ResultSet rs) throws Exception{
		Narudzbenica n = new Narudzbenica();
		n.setIdNarudzbenica(rs.getInt(1));
		n.setDatum(rs.getDate(2));
		n.setKorisnik(DAOFactory.getKorisnikDAO().selectKorisnikById(rs.getInt("Korisnik_idKorisnik")));
		return n;
	}
}
